package com.example.myfirstdemo.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.hardware.Camera;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityOptionsCompat;

import com.example.myfirstdemo.R;
import com.example.myfirstdemo.utils.BaseActivity;

import org.zhx.common.camera.CameraAction;
import org.zhx.common.camera.CameraModel;
import org.zhx.common.camera.CameraPresenter;
import org.zhx.common.camera.CameraProxy;
import org.zhx.common.camera.Constants;
import org.zhx.common.camera.ImageData;
import org.zhx.common.camera.widget.FocusRectView;
import org.zhx.common.util.CameraUtil;
import org.zhx.common.util.ImageUtil;
import org.zhx.common.util.PermissionsUtil;

import java.io.IOException;
import java.util.ArrayList;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class AutoCameraActivity extends BaseActivity implements
        View.OnTouchListener, CameraModel.view<Camera>,
        View.OnClickListener, SurfaceHolder.Callback,
        GLSurfaceView.Renderer {

    private static final String TAG = "AutoCameraActivity";
    private ImageView mShowImage;
    private ImageView mShutterImg; //拍照按钮
    private ImageView mFlashImg;  //闪光灯按钮
    private ImageView mThumImg;  //图库按钮
    private View animateHolder;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mHolder;
    private CameraPresenter mPresenter;
    private int[] modelResId = {
            R.drawable.ic_camera_top_bar_flash_auto_normal,
            R.drawable.ic_camera_top_bar_flash_on_normal,
            R.drawable.ic_camera_top_bar_flash_off_normal,
            R.drawable.ic_camera_top_bar_flash_torch_normal
    };
    private RelativeLayout.LayoutParams showLp;  //RelativeLayout.LayoutParams-改变控件在RelativeLayout界面的位置
    private RelativeLayout mRootView;
    Point screenP,mPreviewPoint;
    FocusRectView mFocusView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = new CameraPresenter(this);
        screenP = CameraUtil.getScreenMetrics(this);
        setContentView(R.layout.autocamera_activity_main);
        getWindow().addFlags((WindowManager.LayoutParams.FLAG_FULLSCREEN));
        mShowImage = findViewById(R.id.z_base_camera_showImg);
        animateHolder = findViewById(R.id.animate_place_holder);
        showLp = (RelativeLayout.LayoutParams) mShowImage.getLayoutParams();
        mShutterImg = findViewById(R.id.z_take_picture_img);
        mSurfaceView = findViewById(R.id.z_base_camera_preview);
        mRootView = findViewById(R.id.root_layout);
        findViewById(R.id.btn_switch_camera).setOnClickListener(this);
        mFlashImg = findViewById(R.id.btn_flash_mode);
        mThumImg = findViewById(R.id.z_thumil_img);
        mThumImg.setOnClickListener(this);
        mFlashImg.setOnClickListener(this);
        mShutterImg.setOnClickListener(this);
        mPresenter.showImages();
        initHolder();
    }

    private void initHolder(){
        mHolder = mSurfaceView.getHolder();
        mHolder.addCallback(this);
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mSurfaceView.setOnTouchListener(this);
    }

    @Override
    public void onError(int msg) {
        super.onError(msg);
        mShutterImg.setEnabled(true);
    }

    @Override
    public void onCameraCreate(CameraProxy<Camera> proxy) throws IOException {
        final RelativeLayout.LayoutParams preViewLp = (RelativeLayout.LayoutParams)
                mSurfaceView.getLayoutParams();
        mPreviewPoint = new Point(proxy.getWidth(),proxy.getHeight());
        preViewLp.width = mPreviewPoint.x;
        preViewLp.height = mPreviewPoint.y;
        mSurfaceView.post(new Runnable() {
            @Override
            public void run() {
                mSurfaceView.setLayoutParams(preViewLp);
            }
        });
        mSurfaceView.setLayoutParams(preViewLp);
        proxy.getCamera().setPreviewDisplay(mHolder);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
                //拍照按钮
            case R.id.z_take_picture_img:
                mShutterImg.setEnabled(false);
                mPresenter.takePictrue();
                break;
                //转换前后置摄像头
            case R.id.btn_switch_camera:
                mPresenter.switchCamera();
                break;
                //闪光灯
            case R.id.btn_flash_mode:
                int position = mPresenter.chanageFlashMode();
                mFlashImg.setImageResource(modelResId[position]);
                break;
                //拍照图库
            case R.id.z_thumil_img:
                if(mImageDatas != null && mImageDatas.size() != 0){
                    Intent intent = new Intent(this,ShowImageActivity.class);
                    //通过activity传递ArrayList<Object>对象
                    intent.putParcelableArrayListExtra(Constants.HISTORE_PICTRUE,
                            (ArrayList<? extends Parcelable> ) mImageDatas);
                    //场景过度动画（转场动画）
                    ActivityOptionsCompat optionsCompat =
                            ActivityOptionsCompat.makeSceneTransitionAnimation
                                    (this,animateHolder,"image");
                    startActivity(intent,optionsCompat.toBundle());
                }
                break;
        }
    }

    @Override
    public void onSaveResult(Uri uri) {
        super.onSaveResult(uri);
        if(mImageDatas == null){
            mImageDatas = new ArrayList<>();
        }
        mImageDatas.add(0,new ImageData(uri));
        if(uri != null){
            try {
                setImageData(uri,true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void setImageData(Uri contentUri, boolean isAnimate) throws IOException {
        final Bitmap bitmap = ImageUtil.getBitmapFormUri(this,contentUri);
        Log.e("CameraPresenter","-------Camera---take complete------"+System.currentTimeMillis());//获取时间戳或测量代码执行的时长
        if(isAnimate){
            mShowImage.setImageBitmap(bitmap);
            //设置拍照成功后图片的动画（场景过度动画）
            mShowImage.animate()
                    .translationX(-(screenP.x / 2 + mThumImg.getX())
                    + CameraUtil.dip2px(this,45))
                    .translationY(screenP.y / 2 - mThumImg.getY()
                    - CameraUtil.dip2px(this,55))
                    .scaleX(0.01f).scaleYBy(0.01f).setDuration(90)
                    .withLayer().withEndAction(new Runnable() {
                @Override
                public void run() {
                    mRootView.removeView(mShowImage);  //图片拖动
                    mShowImage.setImageBitmap(null);
                    mThumImg.setImageBitmap(bitmap);
                    mShowImage = new ImageView(AutoCameraActivity.this);
                    mShowImage.setId(R.id.z_base_camera_showImg);
                    addView(mRootView.getChildCount(),mShowImage,showLp);
                    Log.e("CameraPresenter","-------Camera---show end ---------"
                                +System.currentTimeMillis());
                }
            }).setInterpolator(new AccelerateInterpolator()).start();
            //Interpolator(插值器)负责控制动画变化的速率，
            // 使得基本的动画效果能够以匀速、加速、减速、抛物线速率等各种速率变化
        }else{
            mThumImg.setImageBitmap(bitmap);
        }
    }

    @Override
    public void onTakeComplete() {
        mShutterImg.setEnabled(true);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constants.CAMERA:
                if(grantResults.length > 0 &&grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    startCamera(CameraAction.PERMISSITON_GRANTED);
                }
                break;
            case Constants.STORAGE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    if(PermissionsUtil.hasPermission(this, Manifest.permission.CAMERA)){
                        startCamera(CameraAction.PERMISSITON_GRANTED);
                    }else{
                        PermissionsUtil.requestPermission(this,
                                Manifest.permission.CAMERA,Constants.CAMERA);
                    }
                }
                break;
        }
    }

    private void startCamera(CameraAction action){
        mPresenter.startCamera(action);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        startCamera(CameraAction.SURFACE_CREATE);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mPresenter.releaseCamera(CameraAction.SURFACE_DESTORY);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(v == mSurfaceView){
            if(mFocusView == null){
                mFocusView = new FocusRectView(this);
                RelativeLayout.LayoutParams focusLp = new RelativeLayout.LayoutParams(
                        mPreviewPoint.x,mPreviewPoint.y);
                focusLp.addRule(RelativeLayout.CENTER_IN_PARENT);
                addView(mRootView.getChildCount(),mFocusView,focusLp);
            }
            if(!mPresenter.isFocusing()){
                mFocusView.setVisibility(View.VISIBLE);
                mFocusView.setTouchFoucusRect(event.getX(),event.getY());
                mPresenter.focusArea(event.getX(),event.getY(),mFocusView);
            }
        }
        return false;
    }

    protected void addView(int childCount,View view,RelativeLayout.LayoutParams layoutParams){
        mRootView.addView(view,childCount,layoutParams);
    }



    @Override
    public void onBackPressed() {
        mPresenter.releaseCamera(CameraAction.ON_BACKPRESS);
    }

    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height) {

    }

    @Override
    public void onDrawFrame(GL10 gl) {

    }
}
